package com.riant.test3;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        SimpleClientHttpRequestFactory clientFactory  = new SimpleClientHttpRequestFactory();

        // ConnectTimeout只有在网络正常的情况下才有效，因此两个一般都设置
        clientFactory.setConnectTimeout(5000); //建立连接的超时时间  5秒
        clientFactory.setReadTimeout(5000); // 传递数据的超时时间（在网络抖动的情况下，这个参数很有用）
        ClientHttpRequest client = clientFactory.createRequest(URI.create("https://www.baidu.com"), HttpMethod.GET);
        // 发送请求
        ClientHttpResponse response = client.execute();
        System.out.println(response.getStatusCode()); //200 OK
        System.out.println(response.getStatusText()); // OK
        System.out.println(response.getHeaders()); //

        // 返回内容 是个InputStream
        byte[] bytes = FileCopyUtils.copyToByteArray(response.getBody());
        System.out.println(new String(bytes, StandardCharsets.UTF_8)); // 百度首页内容的html
    }
}
